package com.zfl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ThreeSum {
    public List<List<Integer>> threeSum(int[] nums) {


        List<List<Integer>> res = new ArrayList<>();
        if(nums.length<3) {
            return res;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            int  target=-num;

            if(num>0) {
                break;
            }

            if(i>0&&nums[i]==nums[i-1])
                continue;

            int left=i+1;
            int right=nums.length-1;
            while(left<right) {
                int sum=nums[left]+nums[right];
                if(sum<target) {
                    left++;
                } else if(sum>target) {
                    right--;
                } else {
                    List<Integer> list = List.of(nums[i], nums[left], nums[right]);
                    res.add(list);
                    while(left<right&&nums[left]==nums[left+1]) {
                        left++;
                    }
                    left++;
                    while(left<right&&nums[right]==nums[right-1]) {
                        right--;
                    }
                    right--;
                }
            }
        }
        return res;
    }
}
